package d_静态代码块和同步代码块;

public class MyTicket implements Runnable{
    private static int ticket = 100;


    @Override
    public void run() {
        while(true){
            Thread t = Thread.currentThread();
            String name = t.getName();
            //实现静态代码块
            if("窗口1".equals(name)){
                boolean res = sellTicket();
                if(res){
                    break;
                }
            }

            //实现同步代码块
            if("窗口2".equals(name)){
                synchronized (MyTicket.class){
                    if (ticket > 0){
                        ///出票(卖票) -> 三个窗口在卖
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        System.out.println(t.getName() +"正在卖票:" + ticket );
                        //卖一张少一张
                        ticket--;
                    }else {
                        break;
                    }
                }
            }
        }
    }

    private static synchronized boolean sellTicket() {
        if (ticket == 0) {
            return true;
        } else {
            ///出票(卖票) -> 三个窗口在卖
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Thread t = Thread.currentThread();
            System.out.println(t.getName() + "正在卖票:" + ticket);
            //卖一张少一张
            ticket--;
            return false;
        }
    }

}
